#include "massage.h"
#include "ui_massage.h"
#include "widget.h"
#include <QSqlTableModel>
#include <QVBoxLayout>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QMessageBox>
#include <QStandardItem>
#include <QModelIndex>

massage::massage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::massage)
{
    ui->setupUi(this);
    gx = new gengx; // 确保 gx 指向一个有效的 gengx 对象
    // 设置表头标签之前先确保行列已设置
    ui->tb_widget->setRowCount(1);
    ui->tb_widget->setColumnCount(6); // 假设有6列
    // 设置水平方向的表头标签
    QStringList headerLabels;
    headerLabels << "name"  << "gender"<< "depart" << "wid" << "regist" << "picpath";
    ui->tb_widget->setHorizontalHeaderLabels(headerLabels);
    // 显示表头
    ui->tb_widget->horizontalHeader()->show();
    // 自动调整列宽
    ui->tb_widget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 或者也可以尝试调整列宽以适应内容
    ui->tb_widget->resizeColumnsToContents();
    //创建MySQL数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("43.141.197.129");  // 数据库主机
    db.setPort(29843);
    db.setDatabaseName("face"); // 数据库名
    db.setUserName("zheng");       // 数据库用户名
    db.setPassword("510823qizw@");   // 数据库密码
    if(!db.open())
    {
        qDebug()<<"MySQL数据库打开失败"<<db.lastError().text();
    }
    else
    {
        qDebug()<<"MySQL数据库连接成功";
    }
    qDebug()<<"support drivers:"<<QSqlDatabase::drivers();
    massage_show();
    connect(gx, &gengx::dataUpdated, this, &massage::on_dataUpdated); // 连接信号和槽

}

massage::~massage()
{
    delete ui;
}

void massage::massage_show()
{
    // 查询数据
    QSqlQuery query;
    bool queryOk = query.exec("SELECT name, gender, depart, wid, regist,picpath from emp");
    if (!queryOk)
    {
        qDebug() << "Query failed: " << query.lastError().text();
        return;
    }
    // 获取查询结果的记录集
    QSqlRecord record = query.record();
    int row = 0;
    while (query.next())
    {
        // 插入新行
        ui->tb_widget->insertRow(row);
        // 遍历每一列，并将数据填入表格
        for (int col = 0; col < 6; ++col)
        {
            QString fieldName = record.fieldName(col);
            QTableWidgetItem *item = new QTableWidgetItem(query.value(fieldName).toString());
            ui->tb_widget->setItem(row, col, item);
        }
        ++row;
    }
    // 设置表格的行数
    ui->tb_widget->setRowCount(row);
}

void massage::on_le_search_textChanged(const QString &arg1)
{

    // 构造 SQL 查询条件字符串
    QString strcond = QString(
    "WHERE name LIKE CONCAT('%%', :searchText, '%%') "
    "OR depart LIKE CONCAT('%%', :searchText, '%%') "
    "OR wid LIKE CONCAT('%%', :searchText, '%%') "
    );
    //qDebug()<<"support drivers:"<<QSqlDatabase::drivers();
    QSqlQuery query;
    query.prepare(QString("SELECT name, gender,depart,wid,regist,picpath FROM emp %1").arg(strcond));
    query.bindValue(":searchText", arg1);
    if (!query.exec()) {
    qDebug() << "Query failed:" << query.lastError().text();
    return;
    }
    // 清空表格
    ui->tb_widget->clearContents();
    ui->tb_widget->setRowCount(0);
    // 获取查询结果的记录集
    QSqlRecord record = query.record();
   int row = 0;
    while (query.next()) {
    // 插入新行
    ui->tb_widget->insertRow(row);
   // 遍历每一列，并将数据填入表格
    for (int col = 0; col < record.count(); ++col) {
    QString fieldName = record.fieldName(col);
    QTableWidgetItem *item = new QTableWidgetItem(query.value(fieldName).toString());
    ui->tb_widget->setItem(row, col, item);
    }
    ++row;
    }
   // 设置表格的行数
    ui->tb_widget->setRowCount(row);
}

void massage::on_button_selete_clicked()
{
        QString name;
        int r = ui->tb_widget->currentIndex().row();
        if(r<0)
        {
            QMessageBox::information(nullptr,"信息","无选中员工");
        }
        else if (r >= 0 && r < ui->tb_widget->rowCount())
        {
            // 确保行号有效
            QTableWidgetItem *item = ui->tb_widget->item(r, 0);  // 获取第 r 行第 0 列的项
            if (item)
            {
                name = item->text();  // 获取 name 列的文本值
                qDebug() << "Current row name:" << name;
            }
            else
            {
                qDebug() << "No item found in the current row.";
            }
        }

        QSqlQuery query;
        QString str = "delete from emp where name = :name";
        query.prepare(str);
        query.bindValue(":name", name);
        if(!query.exec())
        {
            qDebug()<<str<<"failed";
            qDebug()<<query.lastError().text();
        }
       // 查询数据
        bool queryOk = query.exec("SELECT name, gender, depart, wid, regist,picpath from emp");
        if (!queryOk)
        {
            qDebug() << "Query failed: " << query.lastError().text();
            return;
        }
        // 获取查询结果的记录集
        QSqlRecord record = query.record();
        int row = 0;
        while (query.next())
        {
            // 插入新行
            ui->tb_widget->insertRow(row);
            // 遍历每一列，并将数据填入表格
            for (int col = 0; col < 6; ++col)
            {
                QString fieldName = record.fieldName(col);
                QTableWidgetItem *item = new QTableWidgetItem(query.value(fieldName).toString());
               ui->tb_widget->setItem(row, col, item);
            }
            ++row;
         }
         // 设置表格的行数
         ui->tb_widget->setRowCount(row);

}

void massage::on_toolButton_clicked()
{
    // 获取当前选中的行
    QList<QTableWidgetItem*> selectedItems = ui->tb_widget->selectedItems(); // 假设 tableWidget 是您的表格视图
    if (!selectedItems.isEmpty()) {
        int currentRow = selectedItems.first()->row(); // 获取选中项所在的行
        // 获取行数据
        gx->le_name->setText(ui->tb_widget->item(currentRow, 0)->text());
        gx->cbb_six->setCurrentText(ui->tb_widget->item(currentRow, 1)->text());
        gx->le_depart->setText(ui->tb_widget->item(currentRow, 2)->text());
        gx->le_wid->setText(ui->tb_widget->item(currentRow, 3)->text());
        gx->le_time->setText(ui->tb_widget->item(currentRow, 4)->text());
        gx->le_image->setText(ui->tb_widget->item(currentRow, 5)->text());
    }
    gx->show();
}

void massage::on_dataUpdated()
{
    massage_show();
}

